<template>
	<w-dailog
		v-model="dialogVisible"
		width="1000px"
		:title="title"
		heightFullscreen
		:showMoreBtn="false"
		:beforeClose="onBeforeClose"
		@close="onRefresh"
	>
		<div class="create-organ" slot-scope="{ fullScreen }">
			<w-scroll-bar :flex="fullScreen">
				<basicInfo
					ref="basicInfo"
					:visibleFlag="dialogVisible"
					:materialDetails="materialDetails"
					:materialSignSelectList="materialSignList"
					@on-materialUnit-change="setMaterialUnitName"
					@on-materialUnitSelect-change="setMaterialSel"
				></basicInfo>
				<detailsInfo
					ref="detailsInfo"
					:materialDetails="materialDetails"
					:tableDetails="tableDetails"
					:fSaveMain="onSaveClickHandler"
					:disabled="false"
					@on-details-refresh="onDetailsRefresh"
				></detailsInfo>
			</w-scroll-bar>
		</div>
		<template slot="footer">
			<el-button @click="onCancelClick">取消</el-button>
			<el-button type="primary" @click="onSaveClick">保存</el-button>
		</template>
	</w-dailog>
</template>
<script>
import basicInfo from './BasicInfo.vue'
import detailsInfo from './DetailsInfo.vue'
export default {
	name: 'createMaterial',
	components: {
		basicInfo,
		detailsInfo
	},
	data () {
		return {
			title: '',
			dialogVisible: false,
			materialDetails: {},
			tableDetails: [],
			materialSignList: [],
			fxDataVerification: this.$fxUtils.fxDataVerification(),
			nextCode: ''
		}
	},
	computed: {
		isAdd () {
			return !this.materialDetails.id
		}
	},
	methods: {
		async add (treeNode) {
			await this.getListData()
			this.materialDetails = {
				id: '',
				code: this.nextCode,
				name: '',
				rate: 100,
				materialSignId: '',
				enable: 1,
				processingFlag: 0,
				materialType: treeNode.id,
				remark: ''
			}
			// this.$refs.basicInfo.addmaterialSign = ''
			this.tableDetails = []
			this.fxDataVerification.resetData(this.materialDetails)
			this.title = '新增物料'
			this.dialogVisible = true
		},
		async edit (materialDetails, tableDetails) {
			await this.getMaterialSignList(materialDetails)
			this.tableDetails = tableDetails
			this.title = '编辑物料'
			this.dialogVisible = true
		},
		async getListData () {
			return Promise.all([this.getNextCode(), this.getMaterialSign()]).then(([nextCode, materialSign]) => {
				this.nextCode = nextCode
				this.materialSignList = materialSign
			})
		},
		async getMaterialSignList (materialDetails) {
			this.getMaterialSign().then((materialSign) => {
				this.materialSignList = materialSign
				this.materialDetails = materialDetails
				const materialUnit = this.materialSignList.find(sign => sign.name === materialDetails.materialUnitName) || {}
				this.materialDetails.materialSignId = materialUnit.id
				// const materialUnit = this.materialSignList.find(sign => sign.id === this.materialDetails.materialSignId) || {}
				// this.$set(this.materialDetails, 'materialUnitName', materialUnit.name)
				this.$set(this.materialDetails, 'materialUnitName', this.materialDetails.materialUnitName || '')
				this.fxDataVerification.resetData(this.materialDetails)
			})
		},
		getNextCode () {
			return this.$fxApi('material.getNextCode')
		},
		getMaterialSign () {
			return this.$fxApi('material.findMaterialSignListAll')
		},
		onRefresh () {
			this.$emit('on-refresh')
		},
		verificationDetails () {
			return this.fxDataVerification.checkComfirm(this.materialDetails)
		},
		onSaveClick () {
			this.$refs.detailsInfo.checkDetailsUnSaving().then(() => {
				if (this.fxDataVerification.checkData(this.materialDetails)) {
					this.$fxMessage.success('保存成功')
				} else {
					this.onSaveClickHandler()
				}
			})
		},
		onSaveClickHandler () {
			return this.onValidateFormData().then(this.onSaveOrganHandler)
		},
		onValidateFormData () {
			return new Promise(resolve => {
				this.$refs.basicInfo.validate().then(() => {
					resolve()
				}).catch(() => {
					this.$fxMessage.warning('请填写必填信息')
				})
			})
		},
		checkUnitName () {
			return new Promise(resolve => {
				this.$refs.basicInfo.checkUnitName(this.tableDetails).then(() => {
					resolve()
				}).catch(() => {
					this.$fxMessage.warning('物料单位不能重复')
				})
			})
		},
		onSaveOrganHandler () {
			const { code, id, name, rate, enable, processingFlag, remark, materialType } = this.materialDetails
			const postData = {
				id,
				code,
				name,
				rate,
				enable,
				processingFlag,
				remark,
				materialType
			}
			const materialUnit = this.materialSignList.find(sign => sign.id === this.materialDetails.materialSignId) || {}
			// 当是新建单位的时候
			if (this.$refs.basicInfo.addmaterialSign) {
				postData.materialSignDTO = {
					id: '',
					name: this.$refs.basicInfo.addmaterialSign
				}
			} else {
				if (this.materialDetails.materialSignId) {
					postData.materialSignDTO = {
						id: this.materialDetails.materialSignId,
						name: materialUnit.name
					}
				}
			}
			this.$set(this.materialDetails, 'materialUnitName', (materialUnit && materialUnit.name) || this.$refs.basicInfo.addmaterialSign)
			if (this.isAdd) {
				return this.$fxApi('material.saveOrUpdate')({ data: postData }).then(res => {
					this.$set(this.materialDetails, 'id', res.data.id)
					this.fxDataVerification.resetData(this.materialDetails)
					return Promise.resolve(res)
				})
			} else {
				if (this.fxDataVerification.checkData(this.materialDetails)) {
					return Promise.resolve(this.materialDetails)
				} else {
					return this.checkUnitName().then(res => {
						return this.$fxApi('material.saveOrUpdate')({ data: postData }).then(res => {
							this.fxDataVerification.resetData(this.materialDetails)
							return Promise.resolve(res)
						})
					})
				}
			}
		},
		onCancelClick () {
			this.verificationDetails().then(() => {
				this.onSaveClickHandler().then(() => {
					this.dialogVisible = false
				})
			}).catch(() => {
				this.dialogVisible = false
			})
		},
		onBeforeClose (close) {
			this.verificationDetails().then(() => {
				this.onSaveClickHandler().then(close)
			}).catch(() => {
				this.dialogVisible = false
			})
		},
		onDetailsRefresh () {
			return this.$fxApi('material.findUnitListByParam')({
				query: {
					relationId: this.materialDetails.id
				}
			}).then(res => {
				// res.result.forEach(item => {
				// 	item.itemUnitList = []
				// })
				this.tableDetails = res
				return Promise.resolve(res)
			})
		},
		setMaterialUnitName (val) {
			this.$set(this.materialDetails, 'materialUnitName', val)
		},
		setMaterialSel (val) {
			const materialUnit = this.materialSignList.find(sign => sign.id === val) || {}
			this.$set(this.materialDetails, 'materialUnitName', materialUnit.name)
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.create-organ {
	flex: 1
	display: flex;
	flex-direction: column;
	overflow: auto;
}
</style>
